package com.leyou.upload.controller;

import com.leyou.upload.service.UploadService;
import com.netflix.ribbon.proxy.annotation.Http;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

/**
 * 上传图片的controller
 */
@Controller
@RequestMapping(value = "upload",produces="text/html;charset=UTF-8" )
public class UploadController {

    @Autowired
    private UploadService uploadService;

    /**
     * 图片上传
     *
     * @param file
     * @return
     */
    @PostMapping("image")
    // MultipartFile是spring类型，代表HTML中form data方式上传的文件，包含二进制数据+文件名称。
    public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) {
        String url = this.uploadService.upload(file);
        // 如果url为null或者空返回失败 400
        if (StringUtils.isBlank(url)) {
            return ResponseEntity.badRequest().build();
        }
        // 如果url没问题返回url
        return ResponseEntity.status(HttpStatus.CREATED).body(url);
    }
}
